package com.briup.corejava.day19;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 补充：管道流，主要用在多线程环境下
 * PipedInputStream
 * PipedOutputStream
 * PipedReader
 * PipedWriter
 */
public class Test7 {
    public static void main(String[] args) {
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        // 管道的口子连起来
        try {
            pis.connect(pos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Thread t1 = new Consumer(pis,"消费者");
        Thread t2 = new Producer(pos,"生产者");
        t1.start();
        t2.start();

    }
}
class Consumer extends Thread{
    private PipedInputStream pis;
    public Consumer(PipedInputStream pis , String name){
        super(name);
        this.pis = pis;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            // 读取数据
            try {
                System.out.println(name+" : "+pis.read());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
class Producer extends Thread{
    private PipedOutputStream pos;
    public Producer(PipedOutputStream pos,String name){
        super(name);
        this.pos = pos;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++){
            try {
                String s = "hello";
                pos.write(s.getBytes());
                System.out.println("第"+i+"次生产数据");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
